We just created our Nodeunit's first unit test. However, it tests
math function in a rather isolated way. I suppose you are wondering
how we can use Nodeunit to test functions with complex arguments
such as HTTP request and response, that are bound to a context.
This is possible using so-called mock objects. They are a
predefined version of the state of complex context-based arguments
or functions, in objects that we want to use in our unit test in order
to test the behavior of our module for the exact state of the object.
To use mock objects, we will need to install a module that supports
object mocking. There are various types of testing tools and
modules available out there. Most of them, however, are designed
to test the JavaScript client functionality. There are modules such
as JsMockito, a JavaScript fork of the famous Mockito framework
for Java, and node-inspector, a module that provides a JavaScript
debugger that starts implicitly in the Google Chrome browser.
Native support for the Chrome browser is logical, since Node.js is
built on top of the Google V8 JavaScript Engine. As we are
developing a server-side application, these are not the most
convenient tools, as JsMockito is not pluggable as a Node.js
module, and using a debugger within your browser to debug backed
applications just doesn't seem right to me. Anyway, if you are about
to dive deeper into Node.js, you should definitely give them a try.
For testing server-side JavaScript modules, we will use the Sinon.JS module.
Like all the other modules, it is available in the npm repository, so execute
the following command to install it:
npm install -g sinon
Sinon.JS is a very flexible JavaScript testing library providing
functionality for mocking, stubbing, and spying on JavaScript
objects. It is available at http://sinonjs.org and can be used with any
JavaScript testing framework. Let's see what we need in order to
test our HTTP module. It exports a single method, handleRequest,
which takes the HTTP request and response objects as arguments.
Based on the requested method, the module calls its internal
functions to handle different requests. Each request handler writes